package com.mz.mattress.admin.api.merchant;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mz.mattress.admin.api.req.CardQueryReq;
import com.mz.mattress.admin.common.Holder;
import com.mz.mattress.admin.service.CardService;
import com.mz.mattress.api.common.Constants;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.entity.Card;
import com.mz.mattress.api.jwt.MerchantJwt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@Slf4j
@RestController
@RequestMapping(Constants.MERCHANT_PATH + "card")
public class CardController {

    @Autowired
    private CardService cardService;

    @GetMapping("/listPage")
    public Result<IPage<Card>> listPage(CardQueryReq req) {

        MerchantJwt userJwt = Holder.MERCHANT_JWT_THREAD_LOCAL.get();
        log.info("typeId={}", userJwt.getTypeId());
        req.setMerchantId(userJwt.getTypeId());

        return cardService.listPage(req);
    }

    @GetMapping("/{id}")
    public Result<Card> detail(@PathVariable Integer id) {
        return cardService.getById(id);
    }

    @PostMapping
    public Result add(@RequestBody Card card) {
        MerchantJwt userJwt = Holder.MERCHANT_JWT_THREAD_LOCAL.get();
        log.info("typeId={}", userJwt.getTypeId());
        card.setMerchantId(userJwt.getTypeId());
        return cardService.add(card);
    }

    @GetMapping("/stop/{id}")
    public Result stop(@PathVariable Integer id) {
        MerchantJwt userJwt = Holder.MERCHANT_JWT_THREAD_LOCAL.get();
        log.info("typeId={}", userJwt.getTypeId());
        return cardService.stop(id);
    }

    @PutMapping
    public Result update(@RequestBody Card card) {

        MerchantJwt userJwt = Holder.MERCHANT_JWT_THREAD_LOCAL.get();
        card.setMerchantId(userJwt.getTypeId());

        if (!card.getMerchantId().equals(userJwt.getTypeId())) {
            return Result.fail("不能修改");
        }

        return cardService.updateById(card);
    }

    @DeleteMapping
    public Result delete(@RequestBody Set<Integer> ids) {
        return cardService.deleteByIds(ids);
    }

}
